package com.jddup.program.dao.statement;

import com.jddup.common.pojo.TableColumn;
import com.jddup.common.pojo.TableMeta;
import com.jddup.program.utils.POJOUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;


/**
 * Created by ZZB on 2017/10/19.
 */
public class UpdatePrepareStatementSetter implements IUpdatePrepareStatementSetter {
    @Override
    public void setInPrepareStatement(PreparedStatement preparedStatement, TableMeta tableMeta, Object object) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException, SQLException {
        int i = 1;
        Object pk = null;
        for (TableColumn tableColumn : tableMeta.getTableColumns()) {
            Object fieldResult = POJOUtils.readDeclaredFieldByGetMethod(object, tableColumn.getPropertyName());
            if(tableColumn.getColumnName().equals(tableMeta.getPrimaryKeyColumn().getColumnName())){
                pk = fieldResult;
                continue;
            }
            if(tableColumn.getPropertyType().equals(Date.class)){
                Instant instant = ((Date)fieldResult).toInstant();
                ZoneId zone = ZoneId.systemDefault();
                LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
                preparedStatement.setObject(i,localDateTime);
            } else {
                preparedStatement.setObject(i,fieldResult);
            }
            i++;
        }
        preparedStatement.setObject(i,pk);
    }

    @Override
    public void setBatchInPrepareStatement(PreparedStatement preparedStatement, TableMeta tableMeta, List<?> objects) throws SQLException, NoSuchMethodException, NoSuchFieldException, IllegalAccessException, InvocationTargetException {
        for (Object object : objects) {
            setInPrepareStatement(preparedStatement, tableMeta, object);
            preparedStatement.addBatch();
        }
    }
}
